package com.ruoyi.exam.utils;

import com.aspose.words.Document;
import com.aspose.words.License;
import com.spire.doc.DocumentObject;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;

public class OfficeToPdf {
    private static boolean getLicense() {
        boolean result = false;
        try {
            InputStream is = OfficeToPdf.class.getClassLoader().getResourceAsStream("license.xml"); //  license.xml应放在..\WebRoot\WEB-INF\classes路径下
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void mergeWord(List<String> words, String destPath){
        com.spire.doc.Document d1 = new com.spire.doc.Document(words.get(0));
        Section lastSection = d1.getLastSection();
        for (int i = 1; i < words.size(); i++) {
            com.spire.doc.Document d2 = new com.spire.doc.Document(words.get(i));
            for (Section section:(Iterable <Section>)d2.getSections()) {
                for (DocumentObject obj:(Iterable <DocumentObject>)section.getBody().getChildObjects()
                ) {
                    lastSection.getBody().getChildObjects().add(obj.deepClone());
                }
            }
        }
        d1.saveToFile(destPath, FileFormat.Docx_2010);

    }

    public static void doc2pdf(String wordPath, String pdfPath) throws Exception {
        if (!getLicense()) {          // 验证License 若不验证则转化出的pdf文档会有水印产生
            return;
        }
        long old = System.currentTimeMillis();
        File file = new File(pdfPath);  //新建一个pdf文档
        FileOutputStream os = new FileOutputStream(file);
        Document doc = new Document(wordPath);                    //Address是将要被转化的word文档
        doc.save(os, com.aspose.words.SaveFormat.PDF);//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
        long now = System.currentTimeMillis();
        os.close();
        System.out.println("共耗时：" + ((now - old) / 1000.0) + "秒");  //转化用时
    }

    /**
     * 递归删除文件
     * @param dirFile
     * @return
     */
    public static boolean deleteFile(File dirFile) {
        // 如果dir对应的文件不存在，则退出
        if (!dirFile.exists()) {
            return false;
        }

        if (dirFile.isFile()) {
            return dirFile.delete();
        } else {

            for (File file : dirFile.listFiles()) {
                deleteFile(file);
            }
        }

        return dirFile.delete();
    }
}
